package com.d3works.apps.sale.service.saleorder;

import com.d3works.app.AppSettings;
import com.d3works.apps.base.rest.http.RequestEventArgs;
import com.d3works.apps.base.rest.http.RestTemplate;
import com.d3works.apps.sale.db.SaleOrder;
import java.util.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class SaleOrderNotifyServiceImpl extends RestTemplate implements SaleOrderNotifyService {

  private final Logger logger = LoggerFactory.getLogger(SaleOrderNotifyServiceImpl.class);

  public String getNotifyServiceUri() {
    return AppSettings.get().get("app.integration.outter.notification");
  }

  @Override
  protected void beforeRequest(RequestEventArgs request) throws Exception {}

  @Override
  public void onOrderUpdate(SaleOrder saleOrder) throws Exception {
    createAndSendNotify(saleOrder, "update");
  }

  @Override
  public void onOrderCreate(SaleOrder saleOrder) throws Exception {
    createAndSendNotify(saleOrder, "save");
  }

  private void createAndSendNotify(SaleOrder saleOrder, String action) throws Exception {
    Map<String, Object> data = new LinkedHashMap<>();
    Map<String, Object> header = new LinkedHashMap<>();
    Map<String, Object> body = new LinkedHashMap<>();
    data.put("header", header);
    data.put("body", body);
    header.put("sys", "erp");
    header.put("type", "project");
    header.put("action", action);

    body.put("orderNo", saleOrder.getSaleOrderSeq());
    String result = this.post(getNotifyServiceUri(), data);
    if (logger.isInfoEnabled()) {
      logger.info("调用通知接口:{}，返回：{}", getNotifyServiceUri(), result);
    }
  }
}
